import 'package:eplorex/pages/message/wx_popup_menu_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:fluwx/fluwx.dart';
import 'package:oktoast/oktoast.dart';
import 'package:tobias/tobias.dart';

class PaymentDemoPage extends StatefulWidget {
  const PaymentDemoPage({super.key});

  @override
  State<PaymentDemoPage> createState() => _PaymentDemoPageState();
}

class _PaymentDemoPageState extends State<PaymentDemoPage> {
  GlobalKey key = GlobalKey();
  Fluwx fluwx = Fluwx();
  Tobias tobias = Tobias();

  Map<String, String> orderInfo = {};

  @override
  void initState() {
    orderInfo = {};

    initWxApi();
  }

  @override
  Widget build(BuildContext context) {
    // debugPaintSizeEnabled = true;
    return Scaffold(
      appBar: AppBar(
        title: Text("支付测试"),
      ),
      body: Center(
        child: Column(
          children: [
            FilledButton(
               key: key,
                onPressed: () {
                  var render= context.findRenderObject();
                  _onMsgTap();
                },
                child: Text("微信支付")),
            FilledButton(
                onPressed: () {
                  paymentAliPay(orderInfo);
                },
                child: Text("支付宝支付")),
          ],
        ),
      ),
    );
  }

  void _onMsgTap() {
    var actions = ['复制', '转发', '删除'];

    Navigator.push(
        key.currentContext!,
        PopupMenuRoute(
            key.currentContext!,
            actions,
            5,
            Colors.red,
            80,
            40,
            null,
            null))
        .then((index) {
      if(index!=null)
        print(index);
    });
  }

  Widget _menuView(num direct) {
    bool isCanRecall = true;
    var _data = ['复制', '转发', '删除'];
    var menuWidth = 150.0;
    if (isCanRecall && direct == 1) {
      _data.add('撤回');
      menuWidth = 200.0;
    }
    return WPopupMenu(
        menuWidth: menuWidth,
        menuHeight: 30,
        decoration: ShapeDecoration(
          shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.all(Radius.circular(5))),
        ),
        onValueChanged: (int selected) {
          switch (_data[selected]) {
            case '复制':
              showToast('复制成功');
              Clipboard.setData(ClipboardData(text: "520"));
              break;
            case '转发':
              _selectMemberPage();
              break;
            case '删除':
              _deleteMsg();
              break;
            case '撤回':
              _recallMsg();
              break;
          }
        },
        pressType: PressType.longPress,
        actions: _data,
        // key: ValueKey("popometn"),
        width: 200,
        height: 60,
        child: _backView(context));
  }


  _backView(BuildContext buildContext){
    return FilledButton(
        onPressed: () {
          _menuView(1);
          // paymentWechat(orderInfo);
        },
        child: Text("微信支付"));
  }

  _deleteMsg(){

  }

  _recallMsg(){

  }

  _selectMemberPage(){

  }


  void initWxApi() {
    fluwx.registerApi(
        appId: "wxd930ea5d5a228f5f",
        universalLink: "https://your.univerallink.com/link/");
  }

  /// 微信支付
  void paymentWechat(orderInfo) async {
    /// 判断手机上是否安装微信
    var result = await fluwx.isWeChatInstalled;
    if (result) {
      Payment payment = Payment(
        appId: orderInfo['appid'],
        partnerId: orderInfo['partnerid'],
        prepayId: orderInfo['prepayid'],
        packageValue: orderInfo['package'],
        nonceStr: orderInfo['noncestr'],
        timestamp: int.parse(orderInfo['timestamp']),
        sign: orderInfo['paySign'],
      );

      await fluwx.pay(which: payment);
      fluwx.addSubscriber((response) {
        if (response.isSuccessful) {
          showToast("微信支付成功");
        } else {
          showToast(response.errStr ?? "微信支付失败");
        }
      });
    } else {
      showToast('该手机上未安装微信,请选择其他支付方式');
    }
  }

  /// 支付宝支付
  void paymentAliPay(orderInfo) async {
    /// 判断手机上是否安装微信
    var result = await tobias.isAliPayInstalled;
    if (result) {
      var payResult = await tobias.pay(orderInfo);
      if (payResult['result'] != null) {
        if (payResult['resultStatus'] == '9000') {
          showToast('支付宝支付成功');
        } else if (payResult['resultStatus'] == '6001') {
          showToast('支付宝支付失败');
        } else {
          showToast('未知错误');
        }
      }
    } else {
      showToast('该手机上未安装支付宝,请选择其他支付方式');
    }
  }
}
